var express = require("express");
var router = express.Router();
// 配置图片上虚拟路由
router.use("/upload", express.static("upload"));

var { MeansCateModel, MeansInfoModel } = require('../model/model')

// 添加部门
router.post("/means_cate_data", async (req, res) => {
    let body = req.body;
    console.log(body);
    // await MeansCateModel.create(body);
    res.send({
      code: 200,
      msg: "添加成功",
    });
  });


// 资料类别列表
router.get("/means_cate_list", async (req, res) => {
    let data = await MeansCateModel.aggregate([
        {
            $lookup: {
                from: "meanscates",
                localField: "_id",
                foreignField: "meanscate_id",
                as: "children",
            }
        }
    ])
    let arr = []
    data.map(el => {
        if (el.level == 1) {
            arr.push(el)
        }
        return el
    })
    let arr1 = []
    let datalist = data.map(el => {
        if (el.level == 0) {
            el.children = arr
            arr1.push(el)
        }
    })
    // console.log(arr1);
    res.send({
        code: 200,
        msg: "展示成功",
        data: arr1
    });
});

// 资料信息列表
router.get("/means_list", async (req, res) => {
    let cateId = req.query.cate_id
    let name = req.query.name
    let namereg = new RegExp(name, "i");
    if (!cateId || cateId === '63e233e517d29590088713bf') {
        var data = await MeansInfoModel.find().populate('MeansSelfCate', 'name')
    } else {
        var data = await MeansInfoModel.find({ MeansSelfCate: cateId }).populate('MeansSelfCate', 'name')
    }
    if (!name) {
        var data = await MeansInfoModel.find().populate('MeansSelfCate', 'name')
    } else {
        var data = await MeansInfoModel.find({ MeansSelfName: namereg }).populate('MeansSelfCate', 'name')
    }

    res.send({
        code: 200,
        msg: "展示成功",
        data,
    });
});

// 添加资料信息
router.post("/means_data_add", async (req, res) => {
    let body = req.body;
    console.log(body);
    // await MeansInfoModel.create(body);
    res.send({
      code: 200,
      msg: "添加成功",
    });
  });

module.exports = router;
